package nyist.media.bean.auth;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import nyist.media.bean.BaseBean;
import nyist.media.entity.admin.MenuAuth;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author dcf
 * @date 2018/12/23
 */
@Getter
@Setter
@NoArgsConstructor
public class MenuTreeBean extends BaseBean {
    private static final long serialVersionUID = 178106246891135862L;

    /**
     * redis缓存的权限key
     */
    public static final String REDIS_CACHE_ALL_AUTHORITY_KEY = "multimedia:admin:auth:all";

    /**
     * 权限ID
     */
    private Long id;

    /**
     * 权限名称
     */
    private String name;

    /**
     * 权限
     */
    private String authority;

    /**
     * 跳转目标
     */
    private String target;

    /**
     * 图标
     */
    private String icon;

    /**
     * 链接地址
     */
    private String href;

    /**
     * 全部权限
     */
    private String authorities;

    /**
     * 是否检查过
     */
    private boolean checked;

    private List<MenuTreeBean> children;

    public MenuTreeBean(MenuAuth auth) {
        setId(auth.getId());
        this.name = auth.getName();
        this.children = auth.getChildren() == null ? Collections.emptyList() : auth.getChildren().stream().map(MenuTreeBean::new).collect(Collectors.toList());
    }

    // 存到缓存里需要用到
    @JsonIgnore
    // 返回到页面上用到
    @JSONField(serialize = true, deserialize = false, name = "authorityArr")
    public String[] getAuthorityArr() {
        if (StringUtils.isEmpty(getAuthorities())) {
            return null;
        }
        return getAuthorities().split(",");
    }

    public static void findChecked(Long[] ids, List<MenuTreeBean> list) {
        Map<Long, Long> map = Stream.of(ids).collect(Collectors.toMap(Function.identity(), Function.identity()));
        findChecked(map, list);
    }

    /**
     * 从所有权限中过滤掉出角色权限
     *
     * @param map  权限信息ID
     * @param list 所有权限
     */
    private static void findChecked(Map<Long, Long> map, List<MenuTreeBean> list) {
        if (list.isEmpty() || map.isEmpty()) {
            return;
        }
        for (int i = 0, len = list.size(); i < len; i++) {
            MenuTreeBean tmp = list.get(i);
            if (map.get(tmp.getId()) != null) {
                map.remove(tmp.getId());
                tmp.setChecked(true);
                list.set(i, tmp);
            }
            findChecked(map, tmp.getChildren());
        }
    }
}
